import React from 'react';
import {Alert, App, Avatar, Button, Card, Divider, Flex, List} from "antd";
import {Link, useLocation, useNavigate} from "react-router-dom";
import useAsyncEffect from "hook/useAsyncEffect";
import RequestHandler from "http/RequestHandler";
import {SecurityRole} from "type/entity/SecurityRole";
import LogFactory from "log/LogFactory";
import {UserSimple} from "type/entity/SecurityUser";
import {CloseOutlined, FullscreenOutlined} from "@ant-design/icons";
import {useAppDispatch} from "storage/redux/hook";
import {deleteRoleById} from "storage/redux/reducer/role";

const log = LogFactory.getLogger("RoleDeleteComponent");
const RoleDeleteComponent = () => {
    const role = useLocation().state as SecurityRole;
    const [data, setData] = React.useState<UserSimple[]>([]);
    const [alertConfig, setAlertConfig] = React.useState<{
        type: "error" | "success" | "info" | "warning",
        message: string
    }>({type: "error", message: "角色存在依赖关系"});
    const [descState, setDescState] = React.useState<boolean>(true);
    const {message} = App.useApp();
    const navigate = useNavigate();
    const dispatch = useAppDispatch();
    log.debug("role: ", role);
    useAsyncEffect(async () => {
        const res = await RequestHandler.get<UserSimple[]>("/manager/admin/user-role/list/" + role.id);
        if (res.success) {
            setData(res.data);
            if (res.data.length === 0) {
                setAlertConfig({type: "info", message: "该角色没有依赖用户"});
                setDescState(false);
            } else {
                setDescState(true);
            }
        }
    });
    const deleteRole = async () => {
        const res = await RequestHandler.delete<number>("/manager/security-role/" + role.id);
        if (res.success) {
            dispatch(deleteRoleById(role.id));
            message.success(`删除角色 ${role.authority} 成功!`);
            navigate("..");
        } else {
            message.warning(`删除角色 ${role.authority} 失败!`);
        }
    };

    const deDependency = async () => {
        const res = await RequestHandler.delete<number>("/manager/admin/user-role/" + role.id);
        if (res.success) {
            setAlertConfig({type: "success", message: "解除依赖成功"});
            setDescState(false);
            message.success(`${role.authority} 解除依赖成功!`);
            // const depRes = await RequestHandler.get<UserSimple[]>("/manager/security-user-role/users/" + role.id);
            // setData(depRes.data);
        } else {
            setAlertConfig({type: "error", message: "解除依赖失败"});
            message.error(`${role.authority} 解除依赖失败!`);
        }
    };

    return (
        <Card title={`角色删除 - ${role.authority}`} extra={<Link to={".."}>角色列表</Link>}>
            <Flex justify={"space-between"} align={"start"}>
                <Button disabled={descState} type={"primary"} danger icon={<CloseOutlined/>}
                        onClick={deleteRole}>删除角色</Button>
                <Alert message={alertConfig.message} type={alertConfig.type} showIcon/>
                <Button disabled={!descState} type={"primary"} onClick={deDependency}
                        icon={<FullscreenOutlined/>}>解除依赖</Button>
            </Flex>
            <Divider/>
            <List
                header={<div style={{fontSize: "16px", fontWeight: "bold"}}>依赖该角色的用户</div>}
                bordered
                dataSource={data}
                renderItem={(item, index) => <List.Item>
                    <List.Item.Meta
                        avatar={<Avatar src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${index}`}/>}
                        title={item.username}
                        description={item.identity}
                    />
                </List.Item>}
            >
            </List>
        </Card>
    );
};

export default RoleDeleteComponent;